<?php


namespace app\service;


use app\model\Article;
use app\model\Comment;
use app\model\Star;

class ArticleService implements BaseService
{
    static $incetance;

    public static function getIncetance(){
        if(ArticleService::$incetance==null){
            ArticleService::$incetance = new ArticleService();
        }
        return ArticleService::$incetance;
    }
    public function getArticle($id){
        return Article::find($id);
    }

    public function getArticleList($data){
        $type = $data['type']==null?1:$data['type'];
        $page = $data['page']==null?1:$data['page'];
        $limit = $data['limit']==null?10:$data['limit'];
        $status = $data['status']==null?1:$data['status'];
        $result = Article::where('type',$type)->where('status',$status)->field('id,title,image_url,type,read_count,create_time')->limit(($page-1)*$limit,$limit)->select();
        foreach ($result as $key=>$value){
            $id=$value['id'];
            //封装comments
            $comments = Comment::where("article_id",$id)->count();
            $value['comments']=$comments;
            //封装stars
            $stars = Star::where("article_id",$id)->count()

            ;
            $value['stars']=$comments;
        }
        return $result;
    }

    public function addArticle($data){
        Article::insert($data);
    }

    public function deleteById($id){
        Article::destroy([$id]);
    }

    public function updateArticle($data){
        $id = $data['id'];
        $article = Article::find($id);
        $article->title = $data['title']==null?$article->title:$data['title'];
        $article->content = $data['content']==null?$article->content:$data['content'];
        $article->type = $data['type']==null?$article->type:$data['type'];
        $article->status = $data['status']==null?$article->status:$data['status'];
        $article->save();
    }
}